<script lang="ts" setup>
import type { Ref } from 'vue'
import { userApi } from '@/request/api'
import { useAppConfig, useProfile } from '@/stores'
import { useConsole, useHideLoading, useLoading, useModal, useNavBack, useRouteGuard, useToast } from '@/utils'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { isEmpty, isNil } from 'lodash-es'
import { reactive, ref } from 'vue'
import { object as zobject, string as zstring } from 'zod'

const appConfig = useAppConfig()
const profile = useProfile()
const form = reactive({
  name: '',
  idCard: '',
})
const readonly = reactive({
  name: false,
  idCard: false,
})
const oid = ref() as Ref<number>

onLoad(async (query) => {
  const zparse = zobject({
    oid: zstring().regex(/^\d+$/).transform(Number),
  }).safeParse(query)
  if (!zparse.success) {
    await useRouteGuard()
    return
  }
  oid.value = zparse.data.oid

  if (!isEmpty(profile.userInfo.name)) {
    form.name = profile.userInfo.name!
    readonly.name = true
  }
  if (!isEmpty(profile.userInfo.idCard)) {
    form.idCard = profile.userInfo.idCard!
    readonly.idCard = true
  }
})

onShow(async () => {
  // #ifdef H5 || MP-ALIPAY
  // NOTE: 后端接口中没有 useAlipayFace 字段，所以应该就不用判断了
  if ((appConfig.appletSet.useAlipayFace?.value ?? '0') !== '1') {
    await queryESignFace()
  }
  // #endif

  // #ifdef MP-WEIXIN
  const wxEnterOption = wx.getEnterOptionsSync()
  if (wxEnterOption.referrerInfo?.extraData?.faceResult?.ErrorCode === 0) {
    await queryESignFace()
  }
  // #endif
})

async function queryESignFace() {
  useLoading(true)
  const [err, res] = await to(userApi.getESignFaceByOid(oid.value))
  useHideLoading()
  if (err) {
    return
  }
  if (!isNil(res)) {
    await useModal({
      content: '您已完成认证',
      showCancel: false,
      confirmText: '返回',
    })
    useNavBack(undefined, '/order/index')
  }
}

async function handleSubmit() {
  const zparse = zobject({
    name: zstring().min(2, { message: '请输入完整姓名' }).trim(),
    idCard: zstring().regex(/(^\d{15}$)|(^\d{18}$)|(^\d{17}X$)/i, { message: '请输入完整身份证' }).trim().toUpperCase(),
  }).safeParse(form)
  if (!zparse.success) {
    useToast(zparse.error.issues[0].message)
    return
  }

  // NOTE: 后端接口中没有 useAlipayFace 字段，所以相较原项目有逻辑改动

  // #ifdef MP-ALIPAY
  // if ((appConfig.appletSet?.useAlipayFace?.value ?? '1') === '1') {
  //    await handleAlipayAuthorize()
  //    return
  // }
  await handleAlipayAuthorize()
  // #endif

  // #ifdef H5
  useLoading(true)
  const [err, res] = await to(userApi.eSignAuthFace({
    ...form,
    oid: oid.value,
  }))
  useHideLoading()
  if (err) {
    return
  }
  location.href = res.resParam.url
  // #endif

  // #ifdef MP-WEIXIN
  // wx.navigateToMiniProgram({
  //   appId: 'wx1cf2708c2de46337',  // 公证签小程序APPID
  //   path: `/pages/face/index?bizToken=${auth.data.resParam.faceToken}`, // 刷脸页面地址
  // })
  // #endif
}

// #ifdef MP-ALIPAY
async function handleAlipayAuthorize() {
  useLoading(true)
  const [apiErr, apiRes] = await to(userApi.authFace({
    ...form,
    oid: oid.value,
  }))
  useHideLoading()
  if (apiErr) {
    return
  }

  my.startAPVerify({
    url: apiRes.url,
    certifyId: apiRes.certifyId,
    success: (res2: Record<string, any>) => {
      useConsole?.log('startAPVerify', res2)
      if (res2.resultStatus === 9000) {
        useToast('认证成功')
      }
    },
  })
}
// #endif
</script>

<template>
  <view class="h-100vh flex flex-col items-center">
    <view class="py-200px">
      <view class="h-240px w-240px overflow-hidden rd-full">
        <ui-avatar></ui-avatar>
      </view>
    </view>

    <view class="w-600px rd-16px bg-white pl-30px">
      <view class="flex items-center b-b-1px b-b-#e4 b-b-solid">
        <view class="w-100px text-26px lh-90px">姓名</view>
        <input v-model="form.name" class="h-90px flex-1 text-26px text-#3" :readonly="readonly.name" maxlength="10" placeholder="请输入姓名">
      </view>
      <view class="flex items-center">
        <view class="w-100px text-26px lh-90px">身份证</view>
        <input v-model="form.idCard" class="h-90px flex-1 text-26px text-#3" :readonly="readonly.idCard" maxlength="18" placeholder="请输入身份证">
      </view>
    </view>

    <view class="py-100px">
      <view class="btn-primary-theme w-600px text-36px lh-90px" @click="handleSubmit">开始认证</view>
    </view>
  </view>
</template>

<style lang="less" scoped></style>
